<?php

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Support\Facades\Log;

class BaseJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * The data of the console job.
     *
     * @var array
     */
    protected $data;

    /**
     * The action name of the console job.
     *
     * @var string
     */
    protected $action;

    /**
     * The unique code for logger
     *
     * @var string
     */
    protected $uid = '';

    /**
     * Create a new job instance.
     *
     * @param $data
     */
    public function __construct($data)
    {
        $this->data = getVal($data, 'data', []);
        $this->action = getVal($data, 'action', 'handler');
        $this->uid = uniqid();
        set_time_limit(0);
    }

    /**
     * Execute the job.
     *
     * @return mixed
     * @throws \Exception
     */
    public function handle()
    {
        if (!$this->uid) {
            $this->uid = uniqid();
        }
        $res = false;
        $this->logger("[START] - data : " . json_encode($this->data, JSON_UNESCAPED_UNICODE));
        try {
            if (method_exists($this, $this->action)) {
                $res = $this->{$this->action}($this->data);
            }
        } catch (\Exception $e) {
            $error = [
                'code' => $e->getCode(),
                'msg' => $e->getMessage(),
                'file' => $e->getFile() . ' : ' . $e->getLine(),
                'type' => 'job',
                'uid' => $this->uid,
                'data' => $this->data,
            ];
            $this->logger("[EXCEPTION] - " . json_encode($error, JSON_UNESCAPED_UNICODE));
            $this->logger("[END]");
            throw new \Exception($error['msg'] . ' @file: ' . $error['file'], $error['code']);
        }
        $this->logger("[END] - res : " . json_encode($res, JSON_UNESCAPED_UNICODE));
        return $res;
    }

    /**
     * Execute the console job.
     *
     * @param $data
     * @return mixed
     */
    public function handler($data = [])
    {
        return true;
    }

    /**
     * log info
     * @param $msg
     * @return bool
     */
    protected function logger($msg)
    {
        $msg = "[JOB][{$this->action}] - [{$this->uid}] - " . $msg;
        Log::info($msg);
        return true;
    }

}
